﻿@using Newtouch.Infrastructure;
@{
    ViewBag.Title = "Accounting";
    Layout = "~/Views/Shared/_Form.cshtml";

    var jhjzDjEditable = (ViewBag.jhjz_dj_editable as bool?) ?? false;
    var from = Context.Request.QueryString["from"];
}
<style>
    .toolbar {
        width: 45% !important;
        margin: 10px 30px 12px;
    }
</style>
<div class="rows mz" style="margin-bottom: 1%;display:none;">
    <form class="rows" style="margin-bottom: 1%;" id="formPat1">
        <div class="panel panel-default">
            <div class="panel-heading navb-bg">
                门诊基本信息
            </div>
            <div style="padding: 2px;padding-right:20px;" id="divPatInfo">
                <table class="form">
                    <tr>
                        <th class="formTitle"><span class="required">*</span><label id="lbl_mzh">病历号/姓名：</label></th>
                        <td class="formValue">
                            <input type="text" class="form-control" id="mzh" name="mzh" placeholder="最少1位字符" />
                            <label id="mz_blh" hidden="hidden"></label>
                            <label id="jzjhmxId" hidden="hidden"></label>
                            <label id="dwjls" hidden="hidden"></label>@*单次计量数，和单次治疗量作比较*@
                            <label id="jjcl" hidden="hidden"></label>@*单次计量数，和单次治疗量作比较*@
                            <label id="mz_czlx" hidden="hidden"></label>@*操作类型 新增0/修改1/删除2*@
                        <td class="formValue" colspan="1">
                            <input type="button" class="btn btn-default btn-md btn-default-color" id="mz_btnsyy" value="查询" onclick="GetPatSerarchView($('#mzh').val());" />
                            <input type="hidden" id="mz_brxz" />
                        </td>
                        <th class="formTitle">姓名：</th>
                        <td class="formValue">
                            <label id="mz_xm" style="width: 150%"></label>
                        </td>
                        <th class="formTitle">性别：</th>
                        <td class="formValue">
                            <label id="mz_xb"></label>
                        </td>
                        <th class="formTitle">年龄：</th>
                        <td class="formValue">
                            <label id="mz_nl"></label>
                        </td>
                    </tr>
                    <tbody class="dispTbody" style="display:none;">
                        <tr>
                            <td class="formTitle">证件号：</td>
                            <td class="formValue" colspan="2">
                                <label id="mz_zjh"></label>
                            </td>
                            <td class="formTitle">手机号：</td>
                            <td class="formValue seWidth">
                                <label id="mz_phone"></label>
                            </td>
                            <th class="formTitle">出生日期：</th>
                            <td class="formValue seWidth">
                                <label id="mz_csny"></label>
                            </td>
                            <th class="formTitle" hidden>就诊时间：</th>
                            <td class="formValue" colspan="2" hidden>
                                <label id="mz_ghsj"></label>
                            </td>
                            <th class="formTitle" hidden>介绍人：</th>
                            <td class="formValue">
                                <label id="mz_jsr" hidden></label>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <div class="fa_icontoggle"><i class="fa fa-angle-double-down icontoggle" style="color:rgb(0, 160, 233);cursor:pointer;"></i></div>
            </div>
        </div>
    </form>
</div>
<div class="rows zy" style="margin-bottom: 1%;">
    <div class="panel panel-default" style="margin-bottom:0;">
        <div class="panel-heading navb-bg">
            住院患者信息
        </div>
        <table class="form" style="width:96%;">
            <tbody>
                <tr>
                    <th class="formTitle">病历号/姓名：</th>
                    <td class="formValue">
                        <input class="form-control" type="text" id="zyh" value="" placeholder="最少1位字符" />
                    </td>
                    <td class="formValue">
                        <input type="button" class="btn btn-default btn-md btn-default-color" title="选择住院患者" id="zy_btnsyy" value="查询" onclick="GetPatSerarchView($('#zyh').val());">
                        <input hidden="hidden" id="btn_search" />
                    </td>
                    <th class="formTitle">姓名：</th>
                    <td class="formValue">
                        <label id="zy_xm"></label>
                    </td>
                    <th class="formTitle">性别：</th>
                    <td class="formValue">
                        <label id="zy_xb"></label>
                    </td>
                    <th class="formTitle">年龄：</th>
                    <td class="formValue">
                        <label id="zy_nl"></label>
                    </td>
                    <th class="formTitle">病人性质：</th>
                    <td class="formValue">
                        <label id="zy_brxzmc"></label>
                    </td>
                </tr>
            </tbody>
            <tbody class="dispTbody" style="display:none;">
                <tr>
                    <th class="formTitle">证件号：</th>
                    <td class="formValue" colspan="2">
                        <label id="zy_zjh"></label>
                    </td>
                    <th class="formTitle">入院诊断：</th>
                    <td class="formValue">
                        <label id="zy_ryzd"></label>
                    </td>
                    <th class="formTitle">手机号：</th>
                    <td class="formValue">
                        <label id="zy_phone"></label>
                    </td>
                    <th class="formTitle">出生日期：</th>
                    <td class="formValue">
                        <label id="zy_csny"></label>
                    </td>
                    <th class="formTitle">入院日期：</th>
                    <td class="formValue">
                        <label id="zy_ryrq"></label>
                    </td>
                </tr>
            </tbody>
        </table>
        <div class="fa_icontoggle"><i class="fa fa-angle-double-down icontoggle" style="color:rgb(0, 160, 233);cursor:pointer;"></i></div>
    </div>
</div>
<div class="rows" style="margin-bottom: 1%;">
    <div class="panel panel-default" style="margin-bottom:0;">
        <div class="panel-heading navb-bg" id="divPanelJzxm">
            记账项目
        </div>
        <div id="divSLMX" style="padding: 2px;padding-right:20px;">
            @if (from == "mz")
            {
                @Html.Partial("AccountingOutpatientInputArea")
            }
            else
            {
                @Html.Partial("AccountingInpatientInputArea")
            }
        </div>
    </div>
</div>
@Html.Partial("_MiddleButtonsView", new Newtouch.HIS.Web.Core.Models.BottomButtonViewModel()
{
    ShowKeyList = new int[] { 2, 3, 6, 9 },
    F2Text = "添加",
    F3Text = "修改",
    F6Text = "删除",
    F9Text = "取消修改",
    F9Hidden = true
})
<style>
    .danger {
        background-color: #274b6d
    }
    .info {
        background-color: #d9edf7
    }
    .complete {
        background-color: #6ff3ad
    }
</style>
<div>
    <table id="gridMX"></table>
</div>
<table style="width:420px;height:20px; margin-top:10px;margin-left:10px; float:left; color:#274b6d">
    <tr>
        <td>
            <label style="height:7px;width:25px;background-color:#6ff3ad; border:1px solid #ddd"></label>
        </td>
        <td>表示已完成</td>
        <td>
            <label style="height:7px;width:25px;background-color:#d9edf7; border:1px solid #ddd"></label>
        </td>
        <td>表示执行中</td>
        <td>
            <label style="height:7px;width:25px;background-color:#f2dede; border:1px solid #ddd"></label>
        </td>
        <td>表示已停止</td>
        <td>
            <label style="height:7px;width:25px;background-color:white;  border:1px solid #ddd"></label>
        </td>
        <td>表示未执行</td>
    </tr>
</table>
@Html.Partial("_BottomButtonsView", new Newtouch.HIS.Web.Core.Models.BottomButtonViewModel()
{
    ShowKeyList = new int[] { 4, 7, 8 },
    F7Text = "模板",
    F8Text = "提交"
})
<script type="text/javascript">
    var respblh;//病历号验证
    var from = $.request("from");
    var patInfoObj = {};//门诊记账，病人基本信息对象

    $('#btn_bottombutton_f3').attr('disabled', 'disabled');
    $('#btn_bottombutton_f6').attr('disabled', 'disabled');

    //门诊登记完成后，跳转过来，初始化
    var keyValue = sessionStorage.getItem("mzh");
    if (!!keyValue) {
        from = "mz";
        GetQueryFphAjax({ mzh: keyValue });
        sessionStorage.removeItem("mzh")
    }

    if (from == 'mz') {
        $('.mz').css("display", "block");
        $('.zy').css("display", "none");
        $('#jzsj').val($.getDate());
    }
    else {
        $('#StartDate').val($.getDate());
    }

    //声明 项目明细 grid
    $("#gridMX").newtouchLocalDataGrid({
        height: $(window).height() - 330,
        unwritten: false,
        colModel: [
            { label: "newid", name: "newid", width: 80, align: "left", hidden: true },
            { label: "jzjhmxId", name: "jzjhmxId", width: 80, align: "left", hidden: true },
            {
                label: '长临', name: 'yzxz', width: 60, hidden: (from == "mz" ? true : undefined), formatter: function (cellvalue) {
                    return cellvalue == "1" ? "临" : "长";
                }
            },
            { label: "收费项目", name: "sfxmCode", align: "left", hidden: true },
            { label: "收费项目", name: "sfxmmc", width: 250, align: "left" },
            { label: "医嘱类型", name: "yzlx", width: 150, align: "left", hidden: true },
            { label: "类别", name: "sfdlCode", width: 50, align: "left", hidden: true },
            { label: "费用类别", name: "sfdlmc", width: 55, align: "left" },
            { label: "单位", name: "dw", width: 40, align: "left" },
            {
                label: "单价(元)", name: "dj", width: 60, align: "left", formatter: "number"
                    , formatoptions: { decimalPlaces: 2, defaultValue: '0.00' }
            },
            { label: "单次治疗量", name: "zll", width: 70, align: "left" },
            { label: (from == "mz" ? "总次数" : "次数"), name: "sl", width: 40, align: "left" },
            {
                label: "执行状态", name: "zxzt", width: 65, align: "left", formatter: function (cellvalue) {
                    return cellvalue == 0 ? "未执行"
                        : cellvalue == 1 ? "执行中"
                        : cellvalue == 2 ? "已完成"
                        : cellvalue == 3 ? "已停止"
                        : ""; //否则应该是未提交
                }
            },
            { label: "最后执行时间", name: "LastEexcutionTime", width: 50, align: "left", hidden: true },
            { label: "备注", name: "bz", align: "left", hidden: true },
            {
                label: "收费日期", name: "jzsj", width: 100, hidden: (from == "mz" ? undefined : true), formatter: function (val) {
                    if (!!val) {
                        return $.getDate({ date: val });
                    }
                    return "";
                }
            },
            {
                label: "开单日期", name: "StartDate", width: 100, hidden: (from == "mz" ? true : undefined), formatter: function (val) {
                    if (!!val) {
                        var date = $.getDate({ date: val });
                        if (date < '2000-01-01') {
                            return '';  //一部分历史数据1970-01-01
                        }
                        return date;
                    }
                    return "";
                }
            },
            { label: "czlx", name: "czlx", hidden: true },
            { label: "dwjls", name: "dwjls", hidden: true }
        ],
        ondblClickRow: function (rowid) {
            gridEditRow(rowid);
        },
        onSelectRow: function (rowid) {
            $('#btn_bottombutton_f3').removeAttr('disabled');
            $('#btn_bottombutton_f6').removeAttr('disabled');
        },
        gridComplete: function (data) {
            var ids = $("#gridMX").jqGrid('getDataIDs');
            for (var i = 0; i < ids.length; i++) {
                var rowData = $("#gridMX").jqGrid('getRowData', ids[i]);
                if (rowData && rowData.zxzt) {
                    if (rowData.zxzt === '执行中') {
                        $('#gridMX tr[id="' + ids[i] + '"]').addClass('info');
                    }
                    else if (rowData.zxzt === '已完成') {
                        $('#gridMX tr[id="' + ids[i] + '"]').addClass('complete');
                    }
                    else if (rowData.zxzt === '已停止') {
                        $('#gridMX tr[id="' + ids[i] + '"]').addClass('danger');
                    }
                }
            }
        }
    });

    //治疗项目选择浮层绑定
    $('#mzh,#zyh').newtouchBatchFloatingSelector({
        width: 500,
        height: 200,
        caption: "选择患者",
        clickautotrigger: true,
        url: "@Url.Action("PatAccountingSearchInfo")",
        ajaxparameters: function ($thisinput) {
            var keyword = $thisinput.val().trim();
            return "keyword=" + keyword + "&from=" + from +"&brzybzType=" + '@((int)EnumZYBZ.Bqz + "," + (int)EnumZYBZ.Djz)';
        },
        itemdbclickhandler: function ($thistr, $thisinput) {
            if (from =="mz") {
                GetQueryFphAjax({ mzh: $thistr.attr('data-mzh') });
            } else if (from=="zy") {
                getPatInfoAjax({ zyh: $thistr.attr('data-mzh') });
            }
           
        },
        colModel: [
            { label: '主键', name: 'patid', hidden: true },
            { label: '病历号', name: 'blh', width: 100, align: 'center' },
            { label: 'brxz', name: 'brxz', align: 'center', hidden: true },
            { label: '病人性质', name: 'brxzmc', width: 80, align: 'center'},
            { label: from == 'mz' ? "门诊号" : "住院号", name: 'mzh', width: 120, align: 'center', key: true },
            //{
            //    label: '挂号时间', name: 'ghsj', width: 120, align: 'left', hidden: true , formatter: function (cellvalue) {
            //        return cellvalue.length > 19 ? cellvalue.substring(0, 19).replace(/T/g, ' ') : ""
            //    }
            //},
            { label: '姓名', name: 'xm', width: 90, align: 'center' },
            { label: '出生年月', name: 'csny', hidden: true, width: 100, align: 'center', hidden: true  },
            {
                label: '性别', name: 'xb', width: 40, align: 'center', formatter: function (cellvalue) {
                    return $.getGender(cellvalue);
                }
            },
            {
                label: '年龄', name: 'nlshow', width: 50, align: 'center', formatter: function (cellvalue, options, rowObject) {
                    return getAgeFromBirthTime({ begin: rowObject.csny }).text;
                }
            }
        ]
    });

    $('#bz').keydownEnterEvent(function (event) {
        if ($('#bz').hasClass('form-an-cur')) { //缺陷-由上一个enter过来的
            $('#bz').removeClass('form-an-cur')
            return;
        }
        if (editingNewid || editingJzjhmxId) {
            $('#btn_bottombutton_f3').trigger('click');
        } else {
            $('#btn_bottombutton_f2').trigger('click');
        }
        return false;
    });

    //治疗项目选择浮层绑定
    $('#sfxmmc').sfxmFloatingSelector({
        djDecimalPlaces: 4,
        searchType: 'sfxm.dwjls',
        width: 850,
        ajaxparameters: function ($thisinput) {
            return "dllb=2&mzzybz=" + (from == 'mz' ? "1" : "2") + "&keyword=" + $.trim($thisinput.val());
        },
        clickautotrigger: true,
        itemdbclickhandler: function ($thistr, $thisinput) {
            if ($thisinput.attr('id') == 'sfxmmc') {
                $('#sfxmmc').val($thistr.attr('data-sfxmmc'));
                $('#sfxmCode').val($thistr.attr('data-sfxmCode'));
                $('#sfdlCode').val($thistr.attr('data-sfdlCode'));
                $('#yzlx').val($thistr.attr('data-yzlx'));
                $('#sfdlmc').val($thistr.attr('data-sfdlmc'));
                '@(jhjzDjEditable.ToString().ToLower())' === 'true'
                     ? $('#dj').val($thistr.attr('data-dj'))
                     : $('#dj').html($thistr.attr('data-dj'));
                $('#dw').html($thistr.attr('data-dw'));
                $('#dwjls').val($thistr.attr('data-dwjls'));
                $('#jjcl').val($thistr.attr('data-jjcl'));
                if (!(from == 'mz')) {
                    $('#sl').val('1');
                }
            }
        }
    });

    //按创建时间 倒叙 排列， 最新创建的 在最前
    var oldxmList = [];   //历史已提交项目List
    var newxmList = [];   //新项目List

    //向gridMX grid里填充数据
    function fillDataToGrid() {
        $("#gridMX").resetSelection();
        $("#gridMX").clearGridData();
        $("#gridMX").newtouchLocalDataGrid({ posttofirst: false }, oldxmList);
        for (var i = 0; i <= newxmList.length; i++) {
            $("#gridMX").newtouchLocalDataGrid(null, newxmList[newxmList.length - i]);
        }
    }

    fillDataToGrid();

    //检查正在编辑的数据（待提交）的完整性
    function checkEditingRowData(rowData) {
        if (!rowData.sfxmCode || !rowData.sfxmmc || !rowData.yzlx || !rowData.sfdlCode || !rowData.sfdlmc) {
            $.modalAlert("请选择收费项目", 'warning');
        }
        else if (rowData.dw == "") {
            $.modalAlert("缺少项目单位信息", 'warning');
        }
        else if (rowData.jjcl == "" || isNaN(rowData.jjcl)) {
            $.modalAlert("缺少项目的计价策略", 'warning');
        }
        else if (rowData.dwjls == "" || isNaN(rowData.dwjls)) {
            $.modalAlert("缺少项目的单位计量数", 'warning');
        }
        else if (rowData.yzlx == '2' && (rowData.zll == "" || isNaN(rowData.zll))) {
            $.modalAlert("缺少项目单次治疗量", 'warning');
        }
        else if (!((/^(\+|-)?\d+$/).test(rowData.zll)) || rowData.zll < 1) {
            $.modalAlert("单次治疗量为大于0的整数", 'warning');
        }
        else if (parseInt(rowData.dwjls) > parseInt(rowData.zll)) {
            $.modalAlert("单次治疗量不能小于单次计量数", 'warning');
        }
        else if (!((/^(([1-9][0-9]*\.[0-9][0-9]*)|([0]\.[0-9][0-9]*)|([1-9][0-9]*)|([0]{1}))$/).test(rowData.dj))) {
            $.modalAlert("单价为不小于0的数字", 'warning');
        }
        else if (rowData.dj == "" || isNaN(rowData.dj)) {
            $.modalAlert("缺少项目单价信息", 'warning');
        }
        else if (!rowData.jzsj && from == 'mz') {
            $.modalAlert("缺少收费日期", 'warning');
        }
        else if (!rowData.StartDate && !(from == 'mz')) {
            $.modalAlert("缺少开单日期", 'warning');
        }
        else if (rowData.sl == "" || isNaN(rowData.sl)) {
            $.modalAlert("缺少执行次数", 'warning');
        }
        else if (!((/^(\+|-)?\d+$/).test(rowData.sl)) || rowData.sl < 1) {
            $.modalAlert("执行次数为大于0的整数", 'warning');
        }
        else {
            return true;
        }
        return false;
    }

    //按钮 事件 start

    //键入住院号 搜索
    $('#btn_search').click(function () {
        var zyh = $('#zyh').val();
        newtouch_globalevent_f4();
        $('#zyh').val(zyh);
        ajaxLoadDataResult();
    });

    var respZyh;

    //加载住院基本信息
    function ajaxLoadDataResult() {
        var zyh = $('#zyh').val();
        if (zyh) {
            $.najax({
                type: "GET",
                url: "/HospitalizationManage/BookkeepInHos/GetAccountingStatusDetail?zyh=" + zyh,
                loading: true,
                success: function (ajaxresp) {
                    respZyh = ajaxresp.data.patInfo.zyh;
                    setPatInfoModel(ajaxresp.data.patInfo);
                    oldxmList = ajaxresp.data.jzjhList;

                    fillDataToGrid();
                    Clearjzxm();
                },
                errorCallback: function (err) {
                    newtouch_globalevent_f4();
                    $('#zyh').trigger('focus');
                }
            });
        }
        else {
            GetPatSerarchView();
        }
    }

    //加载门诊基本信息，根据病历号或者门诊号获取
    function GetQueryFphAjax(obj) {
        $.loading(true, "正在请求数据...");
        $.ajax({
            type: "POST",
            url: "/OutpatientManage/OutpatientAccounting/GetpatientAccountInfoV4",
            data: { mzh: obj.mzh },
            dataType: "json",
            cache: true,
            async: true,
            success: function (ajaxresp) {
                if (ajaxresp.state === 'success') {
                    $("#gridMX").clearGridData();
                    oldxmList = [];   //历史已提交项目List
                    newxmList = [];   //新项目List
                    if (ajaxresp.data.length > 1) {
                        GetPatSerarchView(keyword);
                    } else {
                        if (!!ajaxresp.data.OutpatAccInfoDto) {
                            respblh = ajaxresp.data.OutpatAccInfoDto.mzh;
                            setPatInfoModel(ajaxresp.data.OutpatAccInfoDto); //个人基本信息赋值
                        }
                        if ((!!ajaxresp.data.OptimAccInfoDto) && ajaxresp.data.OptimAccInfoDto.length > 0) {
                            ajaxresp.data.OptimAccInfoDto.forEach(function (val, idx) {
                                ajaxresp.data.OptimAccInfoDto[idx].newid = null;//清空newid值，保证住院和门诊记账逻辑一致
                            });
                            oldxmList = ajaxresp.data.OptimAccInfoDto;
                        }
                        fillDataToGrid();
                        Clearjzxm();
                    }
                } else if (ajaxresp.state === 'error') {
                    $.modalAlert("查询失败", 'error');
                }
            },
            complete: function () {
                $.loading(false);
            }
        });
    }

    //初始化病人信息
    function setPatInfoModel(patModel) {
        if (from == 'mz') {
            $("#mzh").val('@(ViewBag.IsBlh)' === "OFF" ? patModel.blh : patModel.mzh);
            $("#mz_blh").html('@(ViewBag.IsBlh)' === "OFF" ? patModel.mzh : patModel.blh);
            $("#mz_xb").html($.getGender(patModel.xb));
            $("#mz_csny").html((patModel.csny && patModel.csny.length >= 10 ? patModel.csny.substring(0, 10) : ""));
            $("#mz_zjh").html(patModel.zjh);
            $("#mz_jsr").html(patModel.jsr);
            $("#mz_xm").html(patModel.xm);
            $("#mz_nl").html(getAgeFromBirthTime({ begin: patModel.csny }).text);
            $("#mz_phone").html(patModel.phone);
            if (patModel.sycs) {
                $('#sycs').html("&nbsp&nbsp&nbsp&nbsp保险剩余<span style='color:red'>" + patModel.sycs + "</span>次");
            }
            $("#mz_brxz").val(patModel.brxz);
            //加载病人信息
            patInfoObj.xm = patModel.xm; //姓名
            patInfoObj.xb = patModel.xb; //性别
            patInfoObj.csny = patModel.csny;
            patInfoObj.patid = patModel.patid; //病人内码
            patInfoObj.blh = patModel.blh; //病历号
            patInfoObj.zjh = patModel.zjh; //证件号
            patInfoObj.brxz = patModel.brxz;//病人性质
            patInfoObj.mzh = patModel.mzh;//门诊号
        } else {
            $('#zy_xm').html(patModel.xm);
            $('#zy_xb').html($.getGender(patModel.xb));
            $("#zy_nl").html(getAgeFromBirthTime({ begin: patModel.csny }).text);
            $('#zy_ryzd').html(patModel.ryzdmc);
            $('#zy_zjh').html(patModel.zjh);
            $('#zy_phone').html(patModel.phone);
            $('#zy_csny').html(patModel.csny ? patModel.csny.substring(0, 10) : '');
            $('#zy_ryrq').html(patModel.ryrq ? patModel.ryrq.substring(0, 10) : '');
            $('#zy_brxzmc').html(patModel.brxzmc);
        }

    }

    //选择的病人 callback
    function getPatInfoAjax(selePatInfo) {
        $('#zyh').val(selePatInfo.zyh);
        ajaxLoadDataResult();
    }

    //病人查询(门诊或者住院)
    function GetPatSerarchView(keyword) {
        if (from == 'mz') {//门诊病人信息
            var blh = '@(ViewBag.IsBlh)' === "OFF" ? keyword : null;
            var mzh = '@(ViewBag.IsBlh)' === "OFF" ? null : keyword;
            $.modalOpen({
                id: "patSearch",
                title: "患者查询",
                url: "/OutpatientManage/OutpatientRefund/SysPatEntitiesReView?t=" + Math.random() + "&mzh=" + mzh + "&blh=" + blh,
                width: "700px",
                height: "600px",
                callBack: function (iframeId) {
                    top.frames[iframeId].PatDbGrid(); //在弹出窗口事件
                }
            });
        } else {//住院病人信息
            var zyh;
            if (keyword != "" && typeof (keyword) != undefined) {
                zyh = keyword;
            }
            $.modalOpen({
                id: "patSearch",
                title: "患者查询",
                url: "/PatientManage/AccountManage/PatSearchView?brzybzType=" + '@((int)EnumZYBZ.Bqz + "," + (int)EnumZYBZ.Djz)' + "&t=" + Math.random() + "&zyh=" + zyh,
                width: "700px",
                height: "600px",
                callBack: function (iframeId) {
                    top.frames[iframeId].PatDbGrid(); //在弹出窗口事件
                    //调用查询卡号和住院号
                }//窗口点确定的回调函数
            });
        }

    }

    //获取编辑域的对象数据
    function getEditRowData() {
        var data = {
            yzxz: (from == 'mz' ? ($('#sl').val() == 1 ? "1" : "2") : $('[name=yzxz]:checked').val()),
            sfxmCode: $('#sfxmCode').val(),
            sfxmmc: $('#sfxmmc').val(),
            yzlx: $('#yzlx').val(),
            zll: $('#zll').val(),
            dj: '@(jhjzDjEditable.ToString().ToLower())' === 'true'
                ? $('#dj').val()
                : $('#dj').html(),
            dw: $('#dw').html(),
            sl: $('#sl').val(),
            sfdlCode: $('#sfdlCode').val(),
            sfdlmc: $('#sfdlmc').val(),
            bz: $('#bz').val(),
            jzsj: $("#jzsj").nval(),
            StartDate: $("#StartDate").nval(),
            jzjhmxId: $('#jzjhmxId').val(),
            czlx: $('#mz_czlx').val(),
            dwjls: $('#dwjls').val(),
            jjcl: $('#jjcl').val()
        };

        return data;
    }

    var editingNewid = null;    //正在修改的行
    var editingJzjhmxId = null;    //正在修改的行

    //请求 编辑 行
    function gridEditRow(rowid) {
        if (rowid) {
            var rowData = $("#gridMX").jqGrid('getRowData', rowid);
            if (rowData) {
                //20180910add 已提交的不能修改
                if (!rowData.newid) {
                    $.modalAlert("已提交的记账，不能修改", 'warning');
                    return;
                }
                //20180910add 已提交的不能修改
                if (rowData.newid) {
                    //应该是属于newxmList start
                    rowDataArr = $.jsonWhere(newxmList, function (v) {
                        return v && v.newid == rowData.newid;
                    });
                    if (!rowDataArr || rowDataArr.length == 0) {
                        return; //为什么没找到
                    }
                    rowData = rowDataArr[0];  //通过rowData.newid从对象数组中取出该行数据
                    if (true) { //&&可编辑
                        editingJzjhmxId = null;
                        editingNewid = rowData.newid;    //正在修改的行
                    }
                    else {
                        return;
                    }
                    //应该是属于newxmList end
                }
                else if (rowData.jzjhmxId) {
                    //应该是属于oldxmList start
                    //请求编辑已提交的行
                    if (rowData.zxzt == "已完成" || rowData.zxzt == "已停止" || rowData.zxzt == "执行中") {
                        //oldxmList中的多次修改 rowData.zxzt undifined 也没问题
                        $.modalAlert("已执行/已完成/已停止的记录不能修改", 'warning');
                        return;
                    }
                    $('#sfxmmc').attr('disabled', 'disabled').addClass('newtouch_Readonly');//不能修改收费项目
                    rowDataArr = $.jsonWhere(oldxmList, function (v) {
                        return v && v.jzjhmxId == rowData.jzjhmxId;
                    });
                    if (!rowDataArr || rowDataArr.length == 0) {
                        return; //为什么没找到
                    }
                    rowData = rowDataArr[0];  //通过rowData.jzjhmxId从对象数组中取出该行数据
                    if (true) { //&&可编辑
                        editingJzjhmxId = rowData.jzjhmxId;
                        editingNewid = null;    //正在修改的行
                    }
                    else {
                        return;
                    }
                    //应该是属于oldxmList end
                }
                if (!(from == 'mz')) {
                    $('[name=yzxz][value="' + rowData.yzxz + '"]').trigger('click');
                }
                //old new common
                //序列化至编辑域中
                $('#sfxmmc').val(rowData.sfxmmc);
                $('#sfxmCode').val(rowData.sfxmCode);
                $('#yzlx').val(rowData.yzlx);
                $('#sfdlCode').val(rowData.sfdlCode);
                $('#sfdlmc').val(rowData.sfdlmc);
                $('#dw').html(rowData.dw);
                '@(jhjzDjEditable.ToString().ToLower())' === 'true'
                    ? $('#dj').val(parseFloat(!!rowData.dj ? rowData.dj : 0).toFixed(2))
                    : $('#dj').html(parseFloat(!!rowData.dj ? rowData.dj : 0).toFixed(2));
                $('#zll').val(rowData.zll);
                $('#sl').val(rowData.sl);
                $('#bz').val(rowData.bz);
                if (!!rowData.jzsj) {
                    $('#jzsj').val($.getDate({ date: rowData.jzsj, ute: true }));
                }
                if (!!rowData.StartDate) {
                    if ($.getDate({ date: rowData.StartDate }) > '2000-01-01') {
                        $('#StartDate').val($.getDate({ date: rowData.StartDate, ute: true }));
                    }
                    else {
                        //强制补录开单日期
                        $('#StartDate').val('');
                    }
                }
                $('#jzjhmxId').val(rowData.jzjhmxId);
                $('#mz_czlx').val(rowData.czlx);
                $('#dwjls').val(rowData.dwjls);
                $('#jjcl').val(rowData.jjcl);
                $('#btn_bottombutton_f6').attr('disabled', 'disabled');
                $('#btn_bottombutton_f9').show();

                $('#btn_bottombutton_f2').attr('disabled', 'disabled');
            }
        }
    }

    //添加按钮
    function newtouch_event_f2() {
        if (editingNewid || editingJzjhmxId) {
            return; //正在处于修改状态，是不能点击添加按钮的   要disable处理
        }

        if (from == "mz") {
            if (!patInfoObj.mzh) {
                $.modalAlert("缺少患者基本信息", 'warning');
                return;
            }
            if (patInfoObj.mzh !== respblh) {
                $.modalAlert("错误：录入过程中，门诊号变换", 'warning');
                return;
            }
        } else {
            var zyh = $('#zyh').val();
            if (!zyh) {
                $.modalAlert("缺少患者基本信息", 'warning');
                return;
            }
            if (zyh != respZyh) {
                $.modalAlert("错误：录入过程中，住院号变换", 'warning');
                return;
            }
        }
        var addgoon = function () {
            data.czlx = "0";//新增
            data.zxzt = 0;//默认未执行
            //检查重复项

            data.newid = Math.random().toString() + new Date().getMilliseconds();   //newid()

            newxmList.unshift(data);   //作为新项添加 //”数组最前端“

            //重新将xm数组呈现至grid
            fillDataToGrid();

            $('#sfxmmc').val('');
            $('#sfxmCode').val('');
            $('#yzlx').val('');
            $('#sfdlCode').val('');
            $('#sfdlmc').val('');
            $('#dw').html('');
            '@(jhjzDjEditable.ToString().ToLower())' === 'true'
                ? $('#dj').val('')
                : $('#dj').html('');
            $('#zll').val('');
            $('#dwjls').val('');
            $('#jjcl').val('');
            $('#sl').val('');
            $("#mz_czlx").val('');
            setTimeout("$('#sfxmmc').trigger('focus');$('#sfxmmc').trigger('click');", 100);
        }
        var data = getEditRowData();
        if (!(CheckreAdddata(data) && checkEditingRowData(data))) {    //数据是否完善，检查必填项
            return;
        }
        if (data && parseFloat(data.dj) < '0') {
            $.modalAlert("单价为不小于0的数字", 'warning');
            return;
        }
        else if (data && parseFloat(data.dj) == '0') {
            $.modalConfirm("单价为0，确认是否添加", function (flag) {
                if (!flag) {
                    return;
                }
                else {
                    addgoon();
                }
            });
        }
        else {
            addgoon();
        }
    }

    //修改按钮
    function newtouch_event_f3() {
        if (editingNewid && editingJzjhmxId) {
            $.modalConfirm("程序异常，将自动刷新页面", function (flag) {
                location.href = location.href;
            });
            return; //程序错误
        }
        if (editingNewid || editingJzjhmxId) {
            //提交修改
            var data = getEditRowData();
            if (!(checkEditingRowData(data))) {    //数据是否完善，检查必填项
                return;
            }
            var updategoon = function () {

                data.newid = editingNewid;
                data.jzjhmxId = editingJzjhmxId;
                data.zxzt = 0;//修改后的数据默认未执行
                if (!!data.jzjhmxId) {//判断是否新增数据
                    data.czlx = "1";//修改
                    $('#sfxmmc').removeAttr('disabled', 'disabled').removeClass('newtouch_Readonly');
                }
                //检查重复项

                //先在xm数组中找到之
                if (editingNewid) {
                    var matchedIndex = -1;
                    for (var ii = 0; ii < newxmList.length; ii++) {
                        if (newxmList[ii].newid == data.newid) {
                            matchedIndex = ii;
                            break;
                        }
                    }
                    if (matchedIndex == -1) {
                        return; //应该是异常
                    }
                    newxmList.remove(matchedIndex);   //移除该项
                    newxmList.unshift(data);   //作为新项添加    //”数组最前端“
                }
                else {  //editingJzjhmxId
                    var matchedIndex = -1;
                    for (var ii = 0; ii < oldxmList.length; ii++) {
                        if (oldxmList[ii].jzjhmxId == data.jzjhmxId) {
                            matchedIndex = ii;
                            data.LastEexcutionTime = oldxmList[ii].LastEexcutionTime;//最后执行时间不要丢，虽然不需要传到服务器端
                            break;
                        }
                    }
                    if (matchedIndex == -1) {
                        return; //应该是异常
                    }
                    oldxmList.remove(matchedIndex);   //移除该项
                    oldxmList.unshift(data);   //作为新项添加    //”数组最前端“
                }

                //重新将xm数组呈现至grid
                fillDataToGrid();
                $('#sfxmmc').val('');
                $('#sfxmCode').val('');
                $('#yzlx').val('');
                $('#sfdlCode').val('');
                $('#sfdlmc').val('');
                $('#dw').html('');
                '@(jhjzDjEditable.ToString().ToLower())' === 'true'
                    ? $('#dj').val('')
                    : $('#dj').html('');
                $('#zll').val('');
                $('#dwjls').val('');
                $('#jjcl').val('');
                $('#sl').val('');
                $('#mz_czlx').val('');
                $('#jzjhmxId').val('');
                //$('#bz').val('');

                editingNewid = null;    //正在修改的行
                editingJzjhmxId = null;    //正在修改的行

                bottomButtonsReset();

                setTimeout("$('#sfxmmc').trigger('focus');$('#sfxmmc').trigger('click');", 100);
            }
            if (data && parseFloat(data.dj) < '0') {
                $.modalAlert("单价为不小于0的数字", 'warning');
                return;
            }
            else if (data && parseFloat(data.dj) == '0') {
                $.modalConfirm("单价为0，确认是否修改", function (flag) {
                    if (!flag) {
                        return;
                    }
                    else {
                        updategoon();
                    }
                });
            }
            else {
                updategoon();
            }
        }
        else {
            //获取grid当前选中的那一行
            var seleId = $('#gridMX').jqGrid('getGridParam', 'selrow');
            if (seleId) {
                //请求修改该行
                gridEditRow(seleId);
            }
        }
    }

    //F4清除
    function newtouch_event_f4() {
        $('[name=yzxz][value="2"]').trigger('click');
        $("#gridMX").clearGridData();
        $("#jzsj").val($.getDate());
        $("#StartDate").val($.getDate());
        $('#sfxmmc').removeAttr('disabled', 'disabled').removeClass('newtouch_Readonly');
        //jsrq = "";
        oldxmList = [];   //历史已提交项目List
        newxmList = [];   //新项目List
        editingNewid = null;    //正在修改的行
        editingJzjhmxId = null; //正在修改的行
        patInfoObj = {};//门诊记账，病人基本信息对象
        bottomButtonsReset();
    };


    //F6从列表中删除
    function newtouch_event_f6() {
        //获取grid当前选中的那一行
        var rowid = $('#gridMX').jqGrid('getGridParam', 'selrow');
        //请求删除该行
        if (rowid) {
            var rowData = $("#gridMX").jqGrid('getRowData', rowid);
            if (rowData) {
                if (!rowData.newid) {   //该行不能删除，应该是属于oldxmList
                    $.modalAlert("已提交的记账，不能删除", 'warning');
                    return;
                }
                if (rowData.newid == editingNewid) {
                    $.modalAlert("该行正在处于编辑状态，不能删除", 'warning');
                    return; //该行正在处于编辑状态，不能删除
                }

                if (!!rowData.jzjhmxId) {
                    rowData.czlx = "2";
                }
                var matchedIndex = -1;

                if (newxmList.length > 0) {
                    for (var ii = 0; ii < newxmList.length; ii++) {
                        if (newxmList[ii].newid === rowData.newid) {
                            matchedIndex = ii;
                        }
                    }
                }

                if (matchedIndex === -1) {
                    if (oldxmList.length > 0) {
                        for (var ii = 0; ii < oldxmList.length; ii++) {
                            if (oldxmList[ii].jzjhmxId === rowData.jzjhmxId) {
                                matchedIndex = ii;
                            }
                        }
                    }
                    if (matchedIndex === -1) {
                        return; //应该是异常
                    }
                    oldxmList.remove(matchedIndex);   //移除历史记账
                } else {
                    newxmList.remove(matchedIndex);   //移除新记账
                }
                //重新将xm数组呈现至grid
                fillDataToGrid();

                //对其他都不产生影响
            }
        }
    }

    //F7使用模板
    function newtouch_event_f7() {
        if ((from == "mz") && !!!$('#jzsj').val()) {
            $.modalAlert("缺少收费日期", 'warning');
            return;
        }
        if (!(from == "mz") && !!!$('#StartDate').val()) {
            $.modalAlert("缺少开单日期", 'warning');
            return;
        }
        $.modalOpen({
            id: "Form",
            title: "收费项目模板窗口",
            url: "/HospitalizationManage/BookkeepInHos/ChargeItemTemplate?keyValue=",
            width: "700px",
            height: "530px",
            showleftlalbel: true,
            callBack: function (iframeId, isClose) {
                var data = top.frames[iframeId].submitForm();
                $.each(data, function () {
                    var newRowData = {
                        yzxz: (from == 'mz' ? ($('#sl').val() == 1 ? "1" : "2") : $('[name=yzxz]:checked').val()),
                        sfxmCode: this.sfxm,
                        sfxmmc: this.sfxmmc,
                        yzlx: "2",  //项目
                        duration: this.duration,
                        dwjls: this.dwjls,
                        dj: this.dj,
                        dw: this.dw,
                        sl: this.zxcs,
                        sfdlCode: this.dl,
                        sfdlmc: this.dlmc,
                        bz: '',
                        zll: this.zll,
                        zxcs: this.zxcs,
                        jjcl: this.jjcl,
                        jzsj: $('#jzsj').nval(),
                        StartDate: $('#StartDate').nval(),
                        czlx: "0",
                        zxzt: 0

                    };

                    newRowData.newid = Math.random().toString() + new Date().getMilliseconds();   //newid()
                    if (!(checkEditingRowData(newRowData))) {    //数据是否完善，检查必填项
                        return;
                    }
                    if (newRowData.sfxmCode && newRowData.sfdlCode && newRowData.dj && newRowData.dw && newRowData.sl) {
                        newRowData.dj = parseFloat(newRowData.dj);
                        newRowData.sl = parseInt(newRowData.sl);
                        newxmList.unshift(newRowData);   //作为新项添加 //”数组最前端“
                    }
                });

                if (isClose === true) {
                    top.frames[iframeId].$.modalClose();
                }

                fillDataToGrid();
            }
        });
    }

    //F8提交至服务器
    function newtouch_event_f8() {
        if (from == 'mz') {
            mzsubmit();
        } else {
            zysubmit();
        }
    };
    //F9取消修改
    function newtouch_event_f9() {
        $('#sfxmmc').val('');
        $('#sfxmCode').val('');
        $('#yzlx').val('');
        $('#sfdlCode').val('');
        $('#sfdlmc').val('');
        $('#dw').html('');
        '@(jhjzDjEditable.ToString().ToLower())' === 'true'
          ? $('#dj').val('')
          : $('#dj').html('');
        $('#zll').val('');
        $('#dwjls').val('');
        $('#jjcl').val('');
        $('#sl').val('');
        //$('#bz').val('');
        $('#sfxmmc').removeAttr('disabled', 'disabled').removeClass('newtouch_Readonly');
        editingNewid = null;    //正在修改的行
        editingJzjhmxId = null;    //正在修改的行

        $("#gridMX").resetSelection();

        bottomButtonsReset();
        $('#jzjhmxId').val('');
        setTimeout("$('#sfxmmc').trigger('focus');$('#sfxmmc').trigger('click');", 100);
    }
    //按钮重置
    function bottomButtonsReset() {
        $('#btn_bottombutton_f2').removeAttr('disabled');
        $('#btn_bottombutton_f3').attr('disabled', 'disabled');
        $('#btn_bottombutton_f6').attr('disabled', 'disabled');
        $('#btn_bottombutton_f9').hide();
    }

    function mzsubmit() {
        var paramData = [];
        patInfoObj.brxz = $("#mz_brxz").val();
        //paramData.xmList = newxmList;
        var resultxmList = [];
        $.each(newxmList, function () {
            resultxmList.push(this);
        });

        //oldxmList中编辑过的 push到resultxmList中 同时 提交到服务器
        $.each(oldxmList, function () {
            if (this.czlx !== undefined && this.czlx !== null) {
                //zxzt undifined 一定是 历史提交 ， 且 此次修改过
                resultxmList.unshift(this);   //作为新项添加    //”数组最前端“
            }
        });
        paramData.xmList = resultxmList;
        if (!patInfoObj.mzh) {
            $.modalAlert("缺少患者基本信息", 'warning');
            return;
        }
        if (!paramData.xmList || paramData.xmList.length === 0) {
            $.modalAlert("缺少记账计划项目", 'warning');
            return;
        }
        if (patInfoObj.mzh !== respblh) {
            $.modalAlert("错误：录入过程中，门诊号变换", 'warning');
            return;
        }
        $.submitForm({
            url: "/HospitalizationManage/BookkeepInHos/SavepatientAcountInfo",
            param: { bacDto: patInfoObj, xmList: paramData.xmList },
            success: function (ajaxresp) {
                newtouch_globalevent_f4();
                $('#mzh').trigger('focus');
            }
        });
    }

    function zysubmit() {
        var paramData = {};
        paramData.zyh = $('#zyh').val();

        var resultxmList = [];
        $.each(newxmList, function () {
            resultxmList.push(this);
        });

        //oldxmList中编辑过的 push到resultxmList中 同时 提交到服务器
        $.each(oldxmList, function () {
            if (this.czlx !== undefined && this.czlx !== null) {
                //zxzt undifined 一定是 历史提交 ， 且 此次修改过
                resultxmList.unshift(this);   //作为新项添加    //”数组最前端“
            }
        });
        paramData.xmList = resultxmList;
        if (!paramData.zyh) {
            $.modalAlert("缺少患者基本信息", 'warning');
            return;
        }
        if (paramData.zyh != respZyh) {
            $.modalAlert("错误：录入过程中，住院号变换", 'warning');
            return;
        }
        if (!paramData.xmList || paramData.xmList.length == 0) {
            $.modalAlert("缺少记账计划项目", 'warning');
            return;
        }

        for (var k = 0, length = paramData.xmList.length; k < length; k++) {
            if (!checkEditingRowData(paramData.xmList[k])) {
                return;
            }
        }

        $.submitForm({
            url: '/HospitalizationManage/BookkeepInHos/SubmitAccountingPlan',
            param: paramData,
            success: function (data) {
                newtouch_globalevent_f4();
                $('#zyh').trigger('focus');
            }
        });
    }

    //清空记账项目
    function Clearjzxm() {
        $('#sfxmmc').val('');
        $('#sfxmCode').val('');
        $('#yzlx').val('');
        $('#sfdlCode').val('');
        $('#sfdlmc').val('');
        $('#dw').html('');
        '@(jhjzDjEditable.ToString().ToLower())' === 'true'
            ? $('#dj').val('')
            : $('#dj').html('');
        $('#zll').val('');
        $('#dwjls').val('');
        $('#jjcl').val('');
        $('#sl').val('');
        $("#mz_czlx").val('');
        $('#sfxmmc').removeAttr('disabled', 'disabled').removeClass('newtouch_Readonly');
        setTimeout("$('#sfxmmc').trigger('focus');$('#sfxmmc').trigger('click');", 100);
    }

    //判断新增项目是否重复
    function CheckreAdddata(data) {
        for (var ii = 0; ii < newxmList.length; ii++) {
            if (newxmList[ii].sfxmCode == data.sfxmCode && newxmList[ii].jzsj == data.jzsj) {
                $.modalAlert("同一天收费项目不能重复添加", "warning");
                return false;
            }
        }
        return true;
    }
</script>
